package com.strangebreeds.therefromhere.engine;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class DataAccess
{
	private Logger logger = Logger.getLogger(DataAccess.class);
	                                         
	private String query = "select pagelinks.pl_title from pagelinks, page where pagelinks.pl_from = page.page_id and pagelinks.pl_namespace = page.page_namespace	and page.page_namespace = 0	and page.page_title = ?";
	private PreparedStatement queryStatement = null;
	private Connection dbConn;

	{
		org.apache.log4j.PropertyConfigurator.configure("log4j.properties");
		logger.setLevel(Level.DEBUG);	
	}
	
	DataAccess()
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			dbConn = DriverManager
					.getConnection(	Configuration.getDatabaseConnectionString(),
									Configuration.getDatabaseUser(),
									Configuration.getDatabasePassword());
		}
		catch (SQLException e)
		{
			logger.error("SQLException: " + e.getMessage(), e);
		}
		catch (ClassNotFoundException e)
		{
			logger.error("ClassNotFoundException: " + e.getMessage(), e);
		}
	}

	public List<String> getChildPages(String parent)
	{
		List<String> pageList = new ArrayList<String>();

		try
		{
			if (queryStatement == null)
				queryStatement = dbConn.prepareStatement(query);

			queryStatement.setString(1, parent);

			ResultSet rs = queryStatement.executeQuery();

			while (rs.next())
			{
				pageList.add(rs.getString(1));
			}

			rs.close();
		}
		catch (SQLException e)
		{
			logger.error("SQLException: " + e.getMessage(), e);
		}

		return pageList;
	}
}
